var urlConfig = require('../../../src/config');
import api from '@/assets/js/api';//接口API
import store from 'store';
import * as Cookies from "js-cookie";

let systemConfig = function (cb) {
  if (Cookies.getJSON("wawaji_config")) {
    typeof cb == 'function' && cb(Cookies.getJSON("wawaji_config"));
  } else {
    setTimeout(() => {
      systemConfig(cb);
    }, 1000);
  }
}
let userInfo = function () {
  return Cookies.getJSON("wawaji_userinfo") ? Cookies.getJSON("wawaji_userinfo") : {};
}

function login(cb) {
  api.fetch('/api/config').then((res) => {
    Cookies.set("wawaji_config", res.data, {
      expires: 28
    });
    typeof cb == 'function' && cb();
  }).catch();

  updateAccount(cb);
}

function updateAccount(cb) {
  api.fetch('/api/account').then((res) => {
    if (res.data && res.data.id) {
      Cookies.set("wawaji_userinfo", res.data, {
        expires: 28
      });
      typeof cb == 'function' && cb(res.data);
    } else {
      // store.set('apiToken', '')
      let url = window.location.protocol + '//' + window.location.host + '/?#/';
      let uri = encodeURIComponent(url);
      window.location.href = urlConfig.wxLoginUrl + '/api/wechat/oauth?redirect_uri=' + uri;
    }
  }).catch();
}
let setWxTitle = function (title) {
  document.title = title;
  var mobile = navigator.userAgent.toLowerCase();
  if (/iphone|ipad|ipod/.test(mobile)) {
    var iframe = document.createElement('iframe');
    iframe.style.visibility = 'hidden';
    iframe.setAttribute('src', '/static/img/icon_rocker.png');
    var iframeCallback = function () {
      setTimeout(function () {
        iframe.removeEventListener('load', iframeCallback);
        document.body.removeChild(iframe);
      }, 0);
    };
    iframe.addEventListener('load', iframeCallback);
    document.body.appendChild(iframe);
  }
}
export {
  userInfo,
  systemConfig,
  login,
  updateAccount,
  setWxTitle
}
